<template>
  <el-dialog
    title="消耗材盘点单"
    :visible.sync="show"
    width="1000px"
    center
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="100px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="盘点编号" prop="cilNumber">
            <el-input
              v-model="form.cilNumber"
              :disabled="true"
              placeholder="自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点时间" prop="cilTime">
            <el-date-picker
              v-model="form.cilTime"
              style="width: 100%"
              type="date"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="仓库名称" prop="storehouseName">
            <el-input
              v-model="form.storehouseName"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="optType === 'add' ? (showStoreModal = true) : null"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="期次" prop="period">
            <el-input v-model="form.period" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding-bottom: 10px">
        <el-button
          type="primary"
          @click="buttonShowTargetSetListModal"
        >引入盘点</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:createTime="{ row }">
          <!-- <el-input v-model="row.psTime" /> -->
          <el-date-picker
            v-model="row.createTime"
            type="date"
            placeholder="选择日期"
          />
        </template>
        <template v-slot:psNumber="{ row }">
          <el-input v-model="row.psNumber" />
        </template>
        <template v-slot:mtNumber="{ row }">
          <el-input v-model="row.mtNumber" />
        </template>
        <template v-slot:mtName="{ row }">
          <el-input v-model="row.mtName" />
        </template>
        <template v-slot:specification="{ row }">
          <el-input v-model="row.specification" />
        </template>
        <template v-slot:unit="{ row }">
          <el-input v-model="row.unit" />
        </template>
        <template v-slot:dispCount="{ row }">
          <el-input v-model="row.dispCount" />
        </template>
        <template v-slot:useCount="{ row }">
          <el-input v-model="row.useCount" @input="getPlCount" />
        </template>
        <template v-slot:restCount="{ row }">
          <el-input v-model="row.restCount" @focus="count(row)" />
        </template>
        <template v-slot:realCount="{ row }">
          <el-input v-model="row.realCount" @input="getPlCount" />
        </template>
        <template v-slot:plCount="{ row }">
          <el-input v-model="row.plCount" @input="inputPlCount" />
        </template>
        <template v-slot:plAmount="{ row }">
          <el-input v-model="row.plAmount" />
        </template>
        <template v-slot:unitPrice="{ row }">
          <el-input v-model="row.unitPrice" @input="inputUnitPrice" />
        </template>
        <template v-slot:description="{ row }">
          <el-input v-model="row.description" />
        </template>
        <template v-slot:remark="{ row }">
          <el-input v-model="row.remark" />
        </template>
        <template v-slot:options="{ row }">
          <el-button
            type="danger"
            size="mini"
            @click="delRow(row)"
          >删除</el-button>
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <!-- <tree-modal
      title="材料编码选择(多选)"
      :show-modal.sync="showTargetSetListModal"
      :columns="columns"
      :api-obj="{ tree: getMaterialDirectoryTree, list: getMaterialDetailList }"
      @getSelectedRows="getSelectedRows"
    /> -->
    <supplierList3 title="仓库材料" :type="'1'" :show-modal.sync="showTargetSetListModal" :columns="columns" :data-obj="obj" :api-obj="{api:getStorehouseDetailList}" @getSelectedRows="getSelectedRows" />

    <storeList
      :show-modal.sync="showStoreModal"
      @getSelectedData="getStoreSelectedData"
    />
  </el-dialog>
</template>

<script>
import {
  addConsumableInventoryListInfo,
  updateConsumableInventoryListInfo,
  getConsumableInventoryListInfoDetail
} from '@/api/materialManage'
import { getStorehouseDetailList } from '@/api/bigManage'
import storeList from './storeList.vue'

import { getAreaList } from '@/api/common'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import supplierList3 from './supplierList3'
import {
  getMaterialDirectoryTree,
  getMaterialDetailList
} from '@/api/basicCode'
export default {
  name: 'AddConsumableInventoryListInfo',
  components: {
    fileUploader,
    storeList,
    supplierList3
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getMaterialDirectoryTree,
      getMaterialDetailList,
      getStorehouseDetailList,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,
      showStoreModal: false,
      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        cilNumber: '',
        cilTime: '',
        storehouseName: '',
        period: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: '',
        founderUnit: ''
      },
      columns: [
        {
          label: '入库时间',
          prop: 'createTime',
          slot: 'createTime',
          width: '140'
        },
        // {
        //   label: "入库编号",
        //   slot: "psNumber",
        // },
        {
          label: '材料编号',
          prop: 'mtNumber'
        },
        {
          label: '材料名称',
          prop: 'mtName'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '单位',
          prop: 'unit'
        },
        {
          label: '账面数量',
          slot: 'dispCount',
          width: '150'
        },
        {
          label: '使用数量',
          slot: 'useCount',
          width: '150'
        },
        {
          label: '剩余数量',
          slot: 'restCount',
          width: '150'
        },
        {
          label: '实物数量',
          slot: 'realCount',
          width: '150'
        },
        {
          label: '盈亏数量',
          slot: 'plCount',
          width: '150'
        },
        {
          label: '单价',
          slot: 'unitPrice',
          width: '150'
        },
        {
          label: '盈亏金额',
          slot: 'plAmount',
          width: '150'
        },
        {
          label: '描述',
          slot: 'description',
          width: '150'
        },
        {
          label: '备注',
          slot: 'remark',
          width: '150'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '140',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        name: [{ required: true, message: '单位名称', trigger: 'change' }],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: [],
      obj: {}
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    // data: {
    //   handler(newData, oldData) {
    //     if (newData.id) {
    //       this.getDocDetail(newData.id)
    //       Object.keys(this.form).forEach(key => {
    //         const source = newData[key]
    //         if (typeof source === 'boolean') {
    //           this.form[key] = source ? 1 : 0
    //         } else {
    //           this.form[key] = source
    //         }
    //       })
    //     }
    //   },
    //   deep: true,
    //   immediate: true
    // },
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach((key) => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.targetList = []
        this.fileList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    buttonShowTargetSetListModal() {
      if (this.form.storehouseName) {
        this.showTargetSetListModal = true
      } else {
        this.$message.warning('请选择仓库名称')
      }
    },
    getStoreSelectedData(type, data) {
      if (type === 'store') {
        this.obj = {
          name: data.name,
          storehouseInfoId: data.id
        }
        this.form.storehouseName = data.name
      }
    },
    count(row) {
      row.restCount = row.totalCount - row.useCount
      if (isNaN(row.restCount)) {
        row.restCount = ''
      }
    },
    delRow(obj) {
      // this.targetList.map((item, m) => {
      //   if (item.code === obj.code) {
      //     this.targetList.splice(m, 1)
      //   }
      // })
      this.$confirm('确定要删除该材料数据吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.targetList.indexOf(obj)
          if (index > -1) {
            this.targetList.splice(index, 1)
          }
        })
        .catch(() => {})
    },
    getSelectedRows(data) {
      const find = this.targetList.filter((item) => item.mtNumber === data.code)
      if (find.length > 0) {
        this.$message({
          type: 'error',
          message: '同一材料只能盘点一次'
        })
        return
      }

      this.targetList = [
        ...this.targetList,
        {
          ...data,
          mtNumber: data.code,
          mtName: data.name,
          dispCount: data.totalCount,
          count: data.restCount
        }
      ]
      // this.targetList.push(data)
      // this.targetList = [data];
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getConsumableInventoryListInfoDetail({ consumeCheckInfoId: id }).then(
        (res) => {
          const { lstAttachment, lstConsumeCheckDetail } = res.data || {}
          if (lstAttachment && lstAttachment.length > 0) {
            this.fileList = lstAttachment
          }
          if (lstConsumeCheckDetail && lstConsumeCheckDetail.length > 0) {
            this.targetList = lstConsumeCheckDetail
          }
        }
      )
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.targetList.map((item) => {
            item.id = ''
          })
          const params = {
            consumeCheckInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstConsumeCheckDetail: this.targetList.map((item) => {
              return {
                ...item,
                ...(this.optType === 'edit'
                  ? {
                    consumeCheckInfoId: this.data.id
                  }
                  : {})
              }
            })
          }
          const fn =
            this.optType === 'add'
              ? addConsumableInventoryListInfo
              : updateConsumableInventoryListInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    inputPlCount() {
      this.targetList.forEach(item => {
        if (item.plCount && item.unitPrice) {
          item.plAmount = Number.parseFloat(item.plCount) * Number.parseFloat(item.unitPrice)
          item.plAmount = Number.parseFloat(item.plAmount).toFixed(2)
        } else {
          item.plAmount = ''
        }
      })
    },
    inputUnitPrice() {
      this.targetList.forEach(item => {
        if (item.plCount && item.unitPrice) {
          item.plAmount = Number.parseFloat(item.plCount) * Number.parseFloat(item.unitPrice)
          item.plAmount = Number.parseFloat(item.plAmount).toFixed(2)
        } else {
          item.plAmount = ''
        }
      })
    },
    // 获取盈亏数量
    getPlCount() {
      this.targetList.forEach(item => {
        let restCount = 0
        let realCount = 0
        if (item.restCount) {
          restCount = item.restCount
        }
        if (item.realCount) {
          realCount = item.realCount
        }
        // 盈亏数量的计算规则=剩余数量-实物数量
        const plCount = Number.parseFloat(restCount) - Number.parseFloat(realCount)
        item.plCount = plCount.toFixed(2)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409eff;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
